import React, { useState, useEffect } from 'react';
import { Spin } from 'antd';
import _ from 'lodash';
import { TRDefault } from '@/components/index.js';
import { useTablePipeline } from 'ali-react-table';
import { AntdBaseTable } from '@/base/TBaseTable';
import imgStar from '@/assets/img/start_top_right.png';
import type { IDeviationDataType, IIndexListType } from '../../../type';
import { TIME_ENUM, ToFixed } from '../../../tool';
import { ITitleType } from '../../../type';
import { titleMap } from '../../../dictionary';
import { ExplainTitle } from '../../../components';
import styles from './index.less';

interface IProps {
  /**
   * 数据
   */
  data?: IDeviationDataType;
  /**
   * loading
   */
  loading?: boolean;
  /**
   * error
   */
  error?: boolean;
}

interface IDataType extends IIndexListType {
  values: IDataType[];
}

const PredictiveEvaluationRanking = (props: IProps) => {
  const { data, loading, error } = props;
  const pointListOne = TIME_ENUM(24, 'HH:mm');
  const pointListTwo = [{ pointNum: '日总' }, ...TIME_ENUM(24).map((item) => ({ pointNum: item }))];
  const [dataSource, setDataSource] = useState<{
    timeSlotToDeviationIndexList: IDataType[];
    timeSlotToDeviationPowerList: IDataType[];
  }>();

  const dealData = (val: Record<string, IIndexListType[]>) => {
    let _list: any = Object.values(val)
      .find((item) => item?.length > 0)
      ?.map((b) => {
        return {
          dataSourceId: b?.dataSourceId,
          dataSourceName: b?.dataSourceName,
          values: [],
        };
      });
    pointListOne.forEach((a) => {
      const newList: any[] = [];
      _list?.forEach((c: any) => {
        const obj = val[a].find((d: any) => d?.dataSourceId === c?.dataSourceId);
        const item: any = {
          ...c,
          values: [...c?.values, obj],
        };
        newList.push(item);
      });
      _list = _.cloneDeep(newList);
    });
    const _data: any[] = [];
    _list.forEach((item: any) => {
      const a = _.sumBy(item?.values, function (o: any) {
        return o?.deviationValue ?? undefined;
      });
      const _values = [
        {
          ...item,
          deviationValue: a,
        },
        ...item.values,
      ];
      _data.push({
        ...item,
        deviationValue: a,
        values: _values,
      });
    });
    const _dealList: any[] = [];
    let _obj = _.minBy(_data, function (o: any) {
      return o?.deviationValue ?? undefined;
    });
    const minList = _data.filter(
      (item) => ToFixed(_obj?.deviationValue, 3) === ToFixed(item.deviationValue, 3),
    );
    _obj = minList.length > 1 ? _.cloneDeep(minList[1]) : _.cloneDeep(_obj);
    _data.forEach((item) => {
      let _values: any[] = [];
      if (item?.dataSourceId === _obj?.dataSourceId) {
        _values = item?.values?.map((a: any, index: number) => ({
          ...a,
          deviationIndexOptimalFlag: index === 0 ? true : a?.deviationIndexOptimalFlag,
        }));
      } else {
        _values = item?.values?.map((a: any, index: number) => ({
          ...a,
          deviationIndexOptimalFlag: index === 0 ? false : a?.deviationIndexOptimalFlag,
        }));
      }
      _dealList.push({
        ...item,
        values: _values,
      });
    });
    return _dealList;
  };
  useEffect(() => {
    if (data) {
      const _timeSlotToDeviationIndexList = dealData(data?.timeSlotToDeviationIndexList);
      const _timeSlotToDeviationPowerList = dealData(data?.timeSlotToDeviationPowerList);
      setDataSource({
        timeSlotToDeviationIndexList: _timeSlotToDeviationIndexList,
        timeSlotToDeviationPowerList: _timeSlotToDeviationPowerList,
      });
    }
  }, [data]);
  const getColumns = () => {
    const columns = [
      {
        code: 'pointNum',
        name: '评估范围',
        lock: true,
        width: 70,
        align: 'center',
        render(v: number) {
          return <div className={styles.item}>{v ?? '-'}</div>;
        },
      },
      {
        code: 'effectCapacity',
        name: '偏差指数',
        align: 'center',
        children: dataSource?.timeSlotToDeviationIndexList?.map((item) => {
          return {
            code: item?.dataSourceName,
            name: item?.dataSourceName,
            width: 70,
            align: 'center',
            render(v: number, record: any, index: number) {
              return (
                <div className={styles.item}>
                  <div className={styles.value}>
                    {item?.values[index]?.deviationValue ||
                    item?.values[index]?.deviationValue === 0
                      ? ToFixed(item?.values[index]?.deviationValue, 3)
                      : '-'}
                  </div>
                  {item?.values[index]?.deviationIndexOptimalFlag && (
                    <img className={styles.logo} src={imgStar} />
                  )}
                </div>
              );
            },
          };
        }),
      },
      {
        code: 'tendingDateTime',
        name: '偏差功率(MW)',
        align: 'center',
        children: dataSource?.timeSlotToDeviationPowerList?.map((item) => {
          return {
            code: item?.dataSourceName,
            name: item?.dataSourceName,
            width: 70,
            align: 'center',
            render(v: number, record: any, index: number) {
              return (
                <div className={styles.item}>
                  <div className={styles.value}>
                    {item?.values[index]?.deviationValue ||
                    item?.values[index]?.deviationValue === 0
                      ? ToFixed(item?.values[index]?.deviationValue, 3)
                      : '-'}
                  </div>
                  {item?.values[index]?.deviationIndexOptimalFlag && (
                    <img className={styles.logo} src={imgStar} />
                  )}
                </div>
              );
            },
          };
        }),
      },
    ];
    return columns;
  };

  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: pointListTwo, columns: getColumns() as any })
    .primaryKey('id')
    .appendRowPropsGetter((): any => {
      const color = '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <ExplainTitle title={titleMap[ITitleType.PREDICTIVE_EVALUATION_RANKING]?.title} />
      </div>
      <div className={styles.content}>
        {loading ? (
          <Spin />
        ) : error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : dataSource?.timeSlotToDeviationIndexList &&
          dataSource?.timeSlotToDeviationPowerList &&
          dataSource?.timeSlotToDeviationIndexList?.length > 0 &&
          dataSource?.timeSlotToDeviationPowerList?.length > 0 ? (
          <div className={styles.detial}>
            <div className={styles.baseTable}>
              <AntdBaseTable
                useVirtual={{ horizontal: true, vertical: true, header: false }}
                key="id"
                style={{
                  '--row-height': '28px',
                  // '--header-bgcolor': '#383C3E',
                  '--header-row-height': '28px',
                  '--cell-padding': '4px 16px',
                  '--cell-border-vertical': '1px solid var(--bd)',
                  '--header-cell-border-vertical': '1px solid var(--bd)',
                  // '--bgcolor': '#2222629',
                  // '--hover-bgcolor': '#2222629',
                  // '--highlight-bgcolor': '#2222629',
                }}
                {...pipeline.getProps()}
              />
            </div>
          </div>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </div>
  );
};

export default PredictiveEvaluationRanking;
